<template>
  <!-- <center style="width: 100%;"> -->
    <!-- <div style="text-align: center; flex-grow: 1"> -->
    <div>
      <el-form ref="formRef" :inline="true" :model="formData">
        <el-form-item label="习题类型" prop="topicType" >
          <el-select @blur="validFormSubmit(formRef, false, 2)" v-model="formData.topicType"
            clearable
            style="width: 200px;"
            placeholder="请输入习题类型"
          >   
            <el-option
              v-for="item in topicTypeList"
              :key="item.topicType"
              :label="item.topicTypeDesc"
              :value="item.topicType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目范围" prop="min" :rules="[
        { type: 'number', message: '题目范围只能输入数字' }
      ]" >
          <el-input @blur="validFormSubmit(formRef, false, 2)" @input="handleMinChange" v-model.number="formData.min" placeholder="题目范围最小值"/>
          <!-- <span>~</span> -->
        </el-form-item>
        <el-form-item label="~" prop="max" :rules="[
        { type: 'number', message: '题目范围只能输入数字' }
      ]"  >
          <el-input @blur="validFormSubmit(formRef, false, 2)" v-model.number="formData.max" placeholder="题目范围最大值" />
        </el-form-item>
        <!-- <el-form-item label="收藏" prop="isStar" >
          <el-switch v-model="formData.isStar" @change="validFormSubmit(formRef, false, 2)" />
        </el-form-item>
        <el-form-item label="已掌握" prop="isFallible" >
          <el-switch v-model="formData.isFallible" @change="validFormSubmit(formRef, false, 2)" />
        </el-form-item> -->
        <el-form-item label="标签" prop="indexOrder">
          <el-select @blur="validFormSubmit(formRef, false, 2)" v-model="formData.labelIdList" style="width: 200px;" multiple placeholder="请选择标签" >
            <el-option v-for="item in labelList" :key="item.id" :label="item.labelName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="隐藏统计" >
          <el-switch v-model="statisticShow" />
        </el-form-item>
      </el-form>
    </div>
    <div v-show="statisticShow">
      <p>统计：总题数：{{ statisticTopic?.total | 0 }} &nbsp; |
      范围总题数：{{ statisticTopic?.range | 0 }} &nbsp; | 
      已练习题数：{{ statisticTopic?.complete | 0 }} &nbsp; |
      剩余题数：{{ statisticTopic?.range - statisticTopic?.complete | 0 }}</p>
    </div>
    <div>
      <el-row>
        <el-col>
          <el-button type="primary" @click="validFormSubmit(formRef,true,1)">随机练习</el-button>
          <el-button type="primary" @click="validFormSubmit(formRef,false,1)">顺序练习</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- <div style="margin: 0.5%;">
      <el-button :type="starStatus" :icon="Star" v-show="randomdata?.isStar != null" @click="updateLabelTopic(1, starStatus == 'default')" circle />
      <el-button :type="fallibleStatus" :icon="Select" v-show="randomdata?.isFallible != null" @click="updateLabelTopic(2, fallibleStatus == 'default')" circle />
          题目：{{ randomdata?.title }}
    </div> -->
    <div style="margin: 0.5%;">
      <el-button :type="starStatus" :icon="Star" v-show="randomdata?.isStar != null" @click="updateLabelTopic(1, starStatus == 'default')" circle />
      <el-button :type="fallibleStatus" :icon="Select" v-show="randomdata?.isFallible != null" @click="updateLabelTopic(2, fallibleStatus == 'default')" circle />
          题目：{{ randomdata?.title }}
    </div>
    <el-row>
      <el-col>
        <el-button type="primary" @click="showanswer()">查看答案</el-button>
        <ul v-show="showAnswer">
          <li v-for="item in randomdata?.answer">
            {{ item }}
          </li>
        </ul>
      </el-col>
    </el-row>
<!-- </center> -->
<!-- </div> -->
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { postWithToken } from '~/composables/utils';
import {
  Star,CircleClose,CloseBold,Select
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus';

// const route = useRoute();
// const topicType = ref<number | null>(null);
// const getTopicType = () => {
//   if (route.fullPath === '/topic/randomPractice') {
//     topicType.value = 1;
//   } else if (route.fullPath === '/topicElect/randomPractice') {
//     topicType.value = 2;
//   } 
// }
// getTopicType();
const topicTypeList = ref<TopicType[]>();
const getTopicTypeList = async () => {
const response = await postWithToken('/topicType/queryTopicType');
  if (response.code == 200) {
      topicTypeList.value = response.data;
    }
}
const labelList = ref<any>();
getTopicTypeList();

const formRef = ref<FormInstance>();
  const showAnswer = ref<boolean>(false);
  const randomdata = ref<any>(null);
  // 收藏的状态，default是默认样式，就是白色的，表示未收藏，success是就是绿色的样式，表示已收藏
  const starStatus = ref<'success'|'default'>('default');
  const fallibleStatus = ref<'success'|'default'>('default');
  const statisticTopic = reactive({
    total: 0,
    range: 0,
    complete: 0
  });
  const statisticShow = ref<boolean>(false);
  interface TopicType {
    topicType: number,
    topicTypeDesc: string
  }
  interface FormData {
    isRandom: boolean,
    randomNumList:  any,
    // 顺序练习的题目序号
    orderNum: null | number,
    min: number | null,
    max: number | null,
    isStar: boolean,
    isFallible: boolean,
    labelIdList: [],
    topicType: number | '',
    num:1,page:1,size:1
  }

  const formData = reactive<FormData>({
    isRandom: true,
    randomNumList: [],
    // 顺序练习的题目序号
    orderNum: null,
    min: null,
    max: null,
    isStar: false,
    isFallible: false,
    labelIdList: [],
    topicType: '',
    num:1,page:1,size:1
  });


  const validFormSubmit = (formEl: FormInstance | undefined, isRandom:boolean, type:number) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (type == 1) {
        // 随机函数
        // queryTopicNum();
        random(isRandom);
      } else if (type == 2) {
        queryTopicNum();
      }
    } else {
      console.log('error submit!')
    }
  })
}

  const random = async (isRandom:boolean) => {
    showAnswer.value = false;
    formData.isRandom = isRandom;
    try {
      const response = await postWithToken('/topic/randomPractice', formData);
      if (response.code != 200) {
        // 全部随机已完成
        if (response.code == 300) {
          ElMessage.success(response.msg);
          formData.randomNumList = [];
        } else if (response.code == 301) {
          ElMessage.success(response.msg);
          // 全部顺序已完成
          formData.orderNum = null;
        } else if (response.code == 302) {
          // 最小值大于题目总数，清空最小值
          formData.min = null;
        } else if (response.code == 303) {
          // 最小值大于最大值，清空最小值和最大值
          formData.min = null;
          formData.max = null;
        }
      } else {
        if (response.data == null) {
          return
        }
        randomdata.value = response.data[0];
        if (isRandom) {
          formData.randomNumList.push(response.data[0].randomNum);
          // 如果点了随机练习，就清空顺序练习的顺序记录
          formData.orderNum = null;
          // 更新已练习数，-1是因为有个0
          statisticTopic.complete = formData.randomNumList.length;
        } else {
          formData.orderNum = response.data[0].randomNum;
          // 如果点了顺序练习，就清空随机练习的随机记录
          formData.randomNumList = [];
          // 更新已练习数
          var num = 0;
          if (formData.orderNum != null) {
            num = formData.orderNum;
          }
          var num2 = 0;
          if (formData.min != null) {
            num2 = formData.min - 1;
          }
          statisticTopic.complete = num - num2;
        }
      }
      if (randomdata.value.isStar) {
        starStatus.value = 'success';
      } else {
        starStatus.value = 'default';
      }
      if (randomdata.value.isFallible) {
        fallibleStatus.value = 'success';
      } else {
        fallibleStatus.value = 'default';
      }
      
    } catch (error) {
      console.error('There was an error!', error);
    }
  };
  
  const showanswer = () => {
    showAnswer.value = true;
  }
  
  // random(true);

  const handleMinChange = () => {
    formData.orderNum = null;
  }
  
  // 更新标记（收藏、已掌握）
  // labelId 1-收藏 2-已掌握
  // isMarkLabel true-标记 false-取消
  const updateLabelTopic = async (labelId : number, isMarkLabel : boolean) => {
    const updateLabelTopicData = {
      topicIdList: [randomdata.value.id],
      labelId: labelId,
      isMarkLabel: isMarkLabel
    };
    const response = await postWithToken('/label/updateLabelTopic', updateLabelTopicData);
      if (response.code == 200) {
        if (labelId == 1) {
          isMarkLabel ? starStatus.value = 'success' : starStatus.value = 'default';
        } else if (labelId == 2) {
          isMarkLabel ? fallibleStatus.value = 'success' : fallibleStatus.value = 'default';
        }
      } else {
        ElMessage.error(response.msg);
      }
  }

  // 查询总题数
  const queryTopicNum = async () => {
    const response = await postWithToken('/topic/randomPracticeCount', formData);
      if (response.code == 200) {
        statisticTopic.total = response.data.count;
        if (statisticTopic.total == 0) {
          statisticTopic.range = 0;
        } else {
          statisticTopic.range = response.data.max - response.data.min + 1;
        }
        // 清空已练习题目数，清空随机练习和顺序练习记录
        statisticTopic.complete = 0;
        formData.randomNumList = [];
        formData.orderNum = null;
      } else {
        if (response.code == 302) {
          // 最小值大于题目总数，清空最小值
          formData.min = null;
        } else if (response.code == 303) {
          // 最小值大于最大值，清空最小值和最大值
          formData.min = null;
          formData.max = null;
        }
      }
  }

  queryTopicNum();

  const listLabel = async () => {
    var response = await postWithToken('/label/queryLabel', {});
    if (response.code != 200) {
      ElMessage.error(response.msg);
    } else {
      // 所有的角色
      labelList.value = response.data;
      // 已选择的角色
      // updateForm.labelIdList = response.data.filter((item:any) => item.selected).map((item:any) => item.id);
    }
  }
  listLabel();
  </script>

<!-- scoped就是只有该页面生效 -->
<!-- <style lang="scss" scoped>
 .ep-input{
  // width:15%;
}
</style>
   -->